﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Win32;
using Serilog;
using StudentInfoSystem.Core.Interfaces;
using StudentInfoSystem.Core.Models;
using StudentInfoSystem.Core.Models.Enums;
using StudentInfoSystem.Core.Utils;
using StudentInfoSystem.UI.Views.Dialogs;
using StudentInfoSystem.UI.Views.Windows;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using ObservableObject = CommunityToolkit.Mvvm.ComponentModel.ObservableObject;

namespace StudentInfoSystem.UI.ViewModels;
// 新增选项类
public class SearchFieldOption
{
    public SearchField? Field { get; }
    public string DisplayName { get; }

    public SearchFieldOption(SearchField? field, string displayName)
    {
        Field = field;
        DisplayName = displayName;
    }
}

public class SortOptionOption
{
    public SortOption Option { get; }
    public string DisplayName { get; }

    public SortOptionOption(SortOption option, string displayName)
    {
        Option = option;
        DisplayName = displayName;
    }
}

public class StatisticsItem
{
    public required string Title { get; set; }
    public int Value { get; set; }
}

public partial class StudentListViewModel : ObservableObject
{
    private readonly IStudentService _studentService;// 保存对象引用
    private AppSettings _settings;

    // 操作计数器：追踪当前运行的操作数量
    private int _operationCount = 0;
    private DispatcherTimer _loadingTimer;

    // 二级缓存：从_studentService里获取的数据引用
    [ObservableProperty]
    private IEnumerable<Student> _allStudents = [];


    // 三级缓存：当前页数据(把二级缓存分割为若干页)
    [ObservableProperty]
    private ObservableCollection<Student> _currentPageStudents = [];

    // 分页相关属性
    [ObservableProperty]
    [NotifyPropertyChangedFor(nameof(CanGoPrevious), nameof(CanGoNext))]
    private int _currentPage = 1;

    [ObservableProperty]
    [NotifyPropertyChangedFor(nameof(CanGoPrevious), nameof(CanGoNext))]
    private int _pageSize = 10;
    public List<int> PageSizes { get; } = [10, 20, 50, 100];

    [ObservableProperty]
    [NotifyPropertyChangedFor(nameof(CanGoPrevious), nameof(CanGoNext))]
    private int _totalPages;
    [ObservableProperty]
    private int _totalCount;

    [ObservableProperty]
    private bool _canGoPrevious;
    [ObservableProperty]
    private bool _canGoNext;

    // 搜索条件
    [ObservableProperty]
    private SearchField? _selectedSearchField;
    [ObservableProperty]
    private string _searchKeyword = string.Empty;

    // 排序
    [ObservableProperty]
    private SortOption _selectedSortOption = SortOption.ByStudentId;
    public bool ShowSortOrderOption => SelectedSortOption == SortOption.ByStudentId || SelectedSortOption == SortOption.ByDormitory;

    // 加载状态
    [ObservableProperty]
    private bool _isLoading;

    // 添加选中的学生属性
    [ObservableProperty]
    private Student? _selectedStudent;

    [ObservableProperty]
    private int _totalStudentsCount;

    [ObservableProperty]
    private int _totalCollegesCount;

    [ObservableProperty]
    private int _totalHometownsCount;

    [ObservableProperty]
    private int _totalDormitoriesCount;

    [ObservableProperty]
    private int _totalClassesCount;

    [ObservableProperty]
    private int _totalDepartmentsCount;

    [ObservableProperty]
    private ObservableCollection<StatisticsItem> _statisticsItems = new();

    // 添加下拉框选项列表（带中文描述） 属性  变量 box = SearchFieldOptions；
    public List<SearchFieldOption> SearchFieldOptions { get; } =
    [
        new SearchFieldOption(SearchField.StudentId, "学号"),
        new SearchFieldOption(SearchField.Name, "姓名"),
        new SearchFieldOption(SearchField.College, "学院"),
        new SearchFieldOption(SearchField.Department, "系"),
        new SearchFieldOption(SearchField.Class, "班级"),
        new SearchFieldOption(SearchField.Dormitory, "宿舍"),
        new SearchFieldOption(SearchField.Hometown, "籍贯")
    ];

    public List<SortOptionOption> SortOptionOptions { get; } =
    [
        new SortOptionOption(SortOption.ByStudentId, "按学号"),
        new SortOptionOption(SortOption.ByCollege, "按学院"),
        new SortOptionOption(SortOption.ByDormitory, "按宿舍"),
        new SortOptionOption(SortOption.ByDepartment, "按系"),
        new SortOptionOption(SortOption.ByClass, "按班级")
    ];
    

    // 修改原有属性为可观察属性
    [ObservableProperty]
    private SearchFieldOption? _selectedSearchFieldOption;

    [ObservableProperty]
    private SortOptionOption? _selectedSortOptionOption;
    // 升序和降序选项
    [ObservableProperty]
    private bool _isSortOptionAscending;// 默认为升序




    partial void OnSelectedSearchFieldOptionChanged(SearchFieldOption? value)
    {
        SelectedSearchField = value?.Field;
        _settings.SavedSearchField = value?.Field;
    }

    partial void OnSelectedSortOptionOptionChanged(SortOptionOption? value)
    {
        if (value != null)
        {
            SelectedSortOption = value.Option;
            _settings.SavedSortOption = value.Option;
            // 通知 ShowSortOrderOption 属性变更
            OnPropertyChanged(nameof(ShowSortOrderOption));
            // 安全触发异步排序（不等待）
            _ = SafeExecuteAsync(ApplySortInter);
        }
    }

    partial void OnPageSizeChanged(int value)
    {
        _settings.SavedPageSize = value;
        CurrentPage = 1;
        UpdatePagination();
        UpdateCurrentPage();
    }

    partial void OnIsSortOptionAscendingChanged(bool value)
    {
        _settings.SavedIsSortOptionAscending = IsSortOptionAscending;
        // 安全触发异步排序（不等待）
        _ = SafeExecuteAsync(ApplySortInter);
    }

    protected override void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        base.OnPropertyChanged(e);

        if (e.PropertyName is nameof(CurrentPage) or nameof(TotalPages))
        {
            UpdateNavigationProperties();
        }
    }

    private void LoadSettings()
    {
        // 初始化设置
        PageSize = _settings.SavedPageSize > 0 ? _settings.SavedPageSize : PageSizes.First();
        SelectedSearchFieldOption = SearchFieldOptions.FirstOrDefault(o => o.Field == _settings.SavedSearchField) ?? SearchFieldOptions[0];
        SelectedSortOptionOption = SortOptionOptions.FirstOrDefault(o => o.Option == _settings.SavedSortOption) ?? SortOptionOptions[0];
        IsSortOptionAscending = _settings.SavedIsSortOptionAscending;
    }
    // 安全执行异步命令的辅助方法
    private async Task SafeExecuteAsync(Func<Task> asyncOperation)
    {
        try
        {
            StartOperation();
            await asyncOperation();
        }
        catch (Exception ex)
        {
#if DEBUG
            Debug.WriteLine($"StudentListViewModel中操作失败: {ex.Message}");
#endif
            MessageBox.Show($"StudentListViewModel中异步线程操作失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }
        finally
        {
            EndOperation();
        }
    }

    public StudentListViewModel(AppSettings settings)
    {
        _settings = settings;
        _studentService = Bootstrapper.AppHost.Services.GetRequiredService<IStudentService>();
        CurrentPageStudents = [];

        // 初始化加载计时器
        _loadingTimer = new DispatcherTimer
        {
            Interval = TimeSpan.FromMilliseconds(400)
        };
        _loadingTimer.Tick += (s, e) =>
        {
            if (_operationCount > 0)
            {
                IsLoading = true;
            }
        };

        LoadSettings();

        // 监听数据库路径变化
        _settings.PropertyChanged += (s, e) =>
        {
            if (e.PropertyName == nameof(AppSettings.SavedDataBasePath))
            {
                // 数据库路径改变，刷新数据
                _ = SafeExecuteAsync(RefreshData);
            }
        };

        // 延迟加载数据，确保服务已完全启动
        Task.Delay(1000).ContinueWith(_ =>
        {
            Application.Current.Dispatcher.Invoke(() => RefreshData());
        });
    }

    private void StartOperation()
    {
        _operationCount++;
        if (!_loadingTimer.IsEnabled)
        {
            _loadingTimer.Start();
        }
    }

    private void EndOperation()
    {
        if (_operationCount > 0)
        {
            _operationCount--;
        }

        // 所有操作完成时隐藏加载动画
        if (_operationCount == 0)
        {
            _loadingTimer.Stop();
            IsLoading = false;
        }
    }

    [RelayCommand]
    private async Task ApplySearch()
    {
        StartOperation();
        try
        {
            await Task.Run(() =>
            {
                var criteria = new SearchCriteria
                {
                    Keyword = SearchKeyword,
                    Field = SelectedSearchField
                };
                _studentService.Search(criteria);

                // 记录搜索操作日志
                var currentUser = AppSettings.Instance.CurrentUser;
                Log.Information("用户 {UserName} ({Email}) 执行了搜索: {Keyword} (字段: {Field})",
                    currentUser?.Username ?? "未知用户",
                    currentUser?.Email ?? "未知邮箱",
                    SearchKeyword,
                    SelectedSearchField?.ToString() ?? "全部字段");
            });
        }
        finally
        {
            EndOperation();
        }
        await RefreshData();
    }
    private void record(string message)
    {
        // 记录排序操作日志
        var currentUser = AppSettings.Instance.CurrentUser;
        Log.Information($"用户 {currentUser?.Username} ({currentUser?.Email}) " + message);
    }
    private async Task ApplySortInter()
    {
        await Task.Run(() =>
        {
            _studentService.Sort(SelectedSortOption, IsSortOptionAscending);

            // 记录排序操作日志
            var sortOption = IsSortOptionAscending ? "升序" : "降序";
            record($"执行了排序: {SelectedSortOption} ({sortOption})");
        });
        await RefreshData();
    }

    [RelayCommand]
    private async Task ApplySort()
    {
        await SafeExecuteAsync(ApplySortInter) ;
    }

    private async Task RefreshData()
    {
        StartOperation();
        try
        {
            await LoadDataAsync();
        }
        finally
        {
            EndOperation();
        }
    }
    public void RefreshData(IEnumerable<Student> students)
    {
        AllStudents = students;
        UpdatePagination();
        UpdateCurrentPage();
        // 更新统计信息
        TotalStudentsCount = students.Count();
        TotalCollegesCount = students.Select(s => s.College).Distinct().Count();
        TotalHometownsCount = students.Select(s => s.Hometown).Distinct().Count();
        TotalDormitoriesCount = students.Select(s => s.Dormitory).Distinct().Count();
        TotalClassesCount = students.Select(s => s.Class).Distinct().Count();
        TotalDepartmentsCount = students.Select(s => s.Department).Distinct().Count();

        StatisticsItems.Clear();
        StatisticsItems.Add(new StatisticsItem { Title = "学生总数", Value = TotalStudentsCount });
        StatisticsItems.Add(new StatisticsItem { Title = "学院总数", Value = TotalCollegesCount });
        StatisticsItems.Add(new StatisticsItem { Title = "生源地数", Value = TotalHometownsCount });
        StatisticsItems.Add(new StatisticsItem { Title = "宿舍总数", Value = TotalDormitoriesCount });
        StatisticsItems.Add(new StatisticsItem { Title = "班级总数", Value = TotalClassesCount });
        StatisticsItems.Add(new StatisticsItem { Title = "专业总数", Value = TotalDepartmentsCount });
    }
    private async Task LoadDataAsync()
    {
        var primaryCache = await Task.Run(() => _studentService.GetAll());
        AllStudents = await Task.Run(() => _studentService.GetAllFiltered());

        TotalStudentsCount = primaryCache.Count;
        TotalCollegesCount = primaryCache.Select(s => s.College).Distinct().Count();
        TotalHometownsCount = primaryCache.Select(s => s.Hometown).Distinct().Count();
        TotalDormitoriesCount = primaryCache.Select(s => s.Dormitory).Distinct().Count();
        TotalClassesCount = primaryCache.Select(s => s.Class).Distinct().Count();
        TotalDepartmentsCount = primaryCache.Select(s => s.Department).Distinct().Count();
       
        await Application.Current.Dispatcher.InvokeAsync(() =>
        {
            UpdatePagination();
            StatisticsItems.Clear();
            StatisticsItems.Add(new StatisticsItem { Title = "学生总数", Value = TotalStudentsCount });
            StatisticsItems.Add(new StatisticsItem { Title = "学院总数", Value = TotalCollegesCount });
            StatisticsItems.Add(new StatisticsItem { Title = "生源地数", Value = TotalHometownsCount });
            StatisticsItems.Add(new StatisticsItem { Title = "宿舍总数", Value = TotalDormitoriesCount });
            StatisticsItems.Add(new StatisticsItem { Title = "班级总数", Value = TotalClassesCount });
            StatisticsItems.Add(new StatisticsItem { Title = "专业总数", Value = TotalDepartmentsCount });
            UpdateCurrentPage();
        });
    }

    private void UpdatePagination()
    {
        TotalCount = AllStudents.Count();
        TotalPages = TotalCount == 0 ? 1 : (int)Math.Ceiling((double)TotalCount / PageSize);
        CurrentPage = Math.Clamp(CurrentPage, 1, TotalPages);
        UpdateNavigationProperties();
    }

    private void UpdateCurrentPage()
    {
        CurrentPageStudents.Clear();
        var pageItems = AllStudents
            .Skip((CurrentPage - 1) * PageSize)
            .Take(PageSize);

        foreach (var item in pageItems)
        {
            CurrentPageStudents.Add(item);
        }
    }

    private void UpdateNavigationProperties()
    {
        CanGoPrevious = CurrentPage > 1;
        CanGoNext = CurrentPage < TotalPages;
    }

    [RelayCommand]
    private void AddStudent()
    {
        var dialog = new StudentEditDialog();
        // 设置弹窗居中显示
        dialog.Owner = Application.Current.MainWindow;
        dialog.WindowStartupLocation = WindowStartupLocation.CenterOwner;
        if (dialog.ShowDialog() == true)
        {
            var currentUser = AppSettings.Instance.CurrentUser;
            Log.Information("用户 {UserName} ({Email}) 添加了新的学生信息",
                currentUser?.Username ?? "未知用户",
                currentUser?.Email ?? "未知邮箱");

            // 刷新数据
            _ = SafeExecuteAsync(RefreshData);
        }
    }

    [RelayCommand]
    private void EditStudent(Student student)
    {
        if (student == null) return;

        var dialog = new StudentEditDialog(student);
        // 设置弹窗居中显示
        dialog.Owner = Application.Current.MainWindow;
        dialog.WindowStartupLocation = WindowStartupLocation.CenterOwner;

        if (dialog.ShowDialog() == true)
        {
            var currentUser = AppSettings.Instance.CurrentUser;
            Log.Information("用户 {UserName} ({Email}) 编辑了学生 {StudentId} 的信息",
            currentUser?.Username ?? "未知用户",
            currentUser?.Email ?? "未知邮箱",
            student.Id);
            // 刷新数据
            _ = SafeExecuteAsync(RefreshData);
        }
    }

    // 在 StudentListViewModel 类中添加字段
    private bool _sessionDontAskAgain = false;

    [RelayCommand]
    private async Task DeleteStudent(Student student)
    {
        if (student == null) return;

        // 使用会话级别的设置，而不是应用设置
        bool shouldAsk = !_sessionDontAskAgain;

        if (shouldAsk)
        {
            var message = $"确定要删除学生 {student.Name} (学号: {student.Id}) 吗？";

            var (confirmed, dontAsk) = await Application.Current.Dispatcher.InvokeAsync(() =>
                DeleteConfirmationDialog.ShowDialog(message, Application.Current.MainWindow)
            );

            if (!confirmed) return;

            // 只在当前会话中记住选择
            _sessionDontAskAgain = dontAsk;
        }

        StartOperation();
        try
        {
            await Task.Run(() =>
            {
                _studentService.Delete(student.Id);
                // 记录删除操作日志
                var currentUser = AppSettings.Instance.CurrentUser;
                Log.Information("用户 {UserName} ({Email}) 删除了学生 {StudentId}",
                    currentUser?.Username ?? "未知用户",
                    currentUser?.Email ?? "未知邮箱",
                    student.Id);
            });
        }
        finally
        {
            EndOperation();
        }
        await RefreshData();
    }

    [RelayCommand]
    private void GoToFirstPage()
    {
        CurrentPage = 1;
        UpdateCurrentPage();
    }

    [RelayCommand]
    private void GoToLastPage()
    {
        CurrentPage = TotalPages;
        UpdateCurrentPage();
    }

    [RelayCommand]
    private void PreviousPage()
    {
        if (CanGoPrevious)
        {
            CurrentPage--;
            UpdateCurrentPage();
        }
    }

    [RelayCommand]
    private void NextPage()
    {
        if (CanGoNext)
        {
            CurrentPage++;
            UpdateCurrentPage();
        }
    }



    // 添加可搜索字段列表
    public IEnumerable<SearchField> SearchFields =>  Enum.GetValues(typeof(SearchField)).Cast<SearchField>();


    public List<SortOption> SortOptions { get; } = [.. Enum.GetValues(typeof(SortOption)).Cast<SortOption>()];



    [RelayCommand]
    private void ShowAddDialog()
    {
        //var dialog = new StudentEditDialog();
        //if (dialog.ShowDialog() == true)
        //{
        //    _studentService.Add(dialog.Student);
        //    RefreshData();
        //}
    }

    [RelayCommand]
    private void ShowEditDialog(Student student)
    {
        //var dialog = new StudentEditDialog(student);
        //if (dialog.ShowDialog() == true)
        //{
        //    _studentService.Update(dialog.Student);
        //    RefreshData();
        //}
    }


}